import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import  * as  API from '../api/http'

let initialState={
    shoplist:[]
}

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
   r_getshoplist(state,action){//接口数据
    state.shoplist=action.payload
   },
   r_addshoplist(state:any,action){//添加
    state.shoplist.push(action.payload)
   },
   r_editshoplist(state,action){//编辑
   let i= state.shoplist.findIndex(item=>{
        return item.id==action.payload.id
    })
    state.shoplist[i]=action.payload
   },
   r_delshoplist(state,action){//删除
    state.shoplist= state.shoplist.filter(item=>{
        return item.id!==action.payload
    })
   }
  },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;
//异步接口数据
export let async_getshoplist=createAsyncThunk('async_getshoplist',
    async(_,store)=>{
        let res=await API.http_getshoplist()
        // console.log(res);
        store.dispatch(actionfn.r_getshoplist(res))
    }
)
//异步添加
export let async_addshoplist=createAsyncThunk('async_addshoplist',
    async(obj:string,store)=>{
        let res=await API.http_addshoplist(obj)
        store.dispatch(actionfn.r_addshoplist(res))
    }
)
//异步编辑
export let async_editshoplist=createAsyncThunk('async_editshoplist',
    async(obj:string,store)=>{
        let res=await API.http_editshoplist(obj)
        store.dispatch(actionfn.r_editshoplist(res))
    }
)
//异步删除
export let async_delshoplist=createAsyncThunk('async_delshoplist',
    async(id:string,store)=>{
        await API.http_delshoplist(id)
        store.dispatch(actionfn.r_delshoplist(id))
    }
)
//异步搜索名称
export let async_searchname=createAsyncThunk('async_searchname',
    async(name:string,store)=>{
        let res=await API.http_searchname(name)
        store.dispatch(actionfn.r_getshoplist(res))
    }
)
//异步搜索参数键名
export let async_searchkeyname=createAsyncThunk('async_searchkeyname',
    async(keyname:string,store)=>{
        let res=await API.http_searchkeyname(keyname)
        store.dispatch(actionfn.r_getshoplist(res))
    }
)
//搜索状态
export let async_searchCollect=createAsyncThunk('async_searchCollect',
    async(Collect:string,store)=>{
         let res=await API.http_searcgCollect(Collect)
        store.dispatch(actionfn.r_getshoplist(res))
    }
)